﻿using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Narwhunderful.Aphelia.Framework.Graphics
{

    public class TextureInformation : UpdatableComponent
    {

        Texture2D _texture;
        public Texture2D Texture
        {
            get
            {
                return _texture;
            }
            set
            {
                _texture = value;
            }
        }
        
        Rectangle _cacheRectangle = Rectangle.Empty;
        public Rectangle CacheRectangle
        {
            get
            {
                return _cacheRectangle;
            }
            set
            {
                if (_cacheRectangle.X < 0) _cacheRectangle.X = 0;
                if (_cacheRectangle.Y < 0) _cacheRectangle.Y = 0;
                _cacheRectangle = value;
            }
        }

        Color[] _pixelsCache;
        public Color[] PixelsCache
        {
            get
            {
                return _pixelsCache;
            }
        }

        public TextureInformation(Game game)
            : base(game)       
        {
            base.AlwaysNeedsUpdate = false;
            base.NeedsUpdate = true;
        }

        public TextureInformation(Game game, Texture2D texture)
            : base(game)
        {
            _texture = texture;
        }

        #region IUpdatableComponent

        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);
            CachePixels();
        }

        #endregion

        protected virtual void CachePixels()
        {
            if (_texture == null) return;
            if (_texture.Width <= 0 || _texture.Height <= 0) return;
            _pixelsCache = new Color[_cacheRectangle.Width * _cacheRectangle.Height];
            if (_cacheRectangle == Rectangle.Empty) return;
            if (_cacheRectangle.Width <= 0 || _cacheRectangle.Height <= 0) return;
            _texture.GetData<Color>(0, _cacheRectangle, _pixelsCache, 0, _cacheRectangle.Width * _cacheRectangle.Height);
        }

        public Color GetPixelFromCache(int x, int y)
        {
            if (x > _cacheRectangle.Width || x < 0) return Color.Transparent;
            if (y > _cacheRectangle.Width || y < 0) return Color.Transparent;
            return _pixelsCache[x + y * _cacheRectangle.Width];
        }

    }

}
